<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
      <!-- 角色列表 -->
      <el-table :data="rolesList" stripe border>
        <!-- 折叠权限 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格 -->
            <el-row :class="['bd-bottom', i1 === 0 ? 'bd-top' : '', 'vcenter']"
            v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag type="success" closable disable-transitions
                @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bd-top', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable disable-transitions @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable disable-transitions @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="600px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="showDeleteMesBox(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="showRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="rightDialogVisible" width="30%" @close="clearDefKeys">
      <span>
        <el-tree :data="rightsList" :props="rightsProps" show-checkbox node-key="id"
        default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="30%">
      <el-form :model="editRoleForm" label-width="100px" :rules="editRoleFormRules" ref="editRoleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="30%" @close="resetAddRoleForm">
      <el-form :model="addRoleForm" label-width="100px" :rules="addRoleFormRules" ref="addRoleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 接收数据
      rolesList: [],
      // 分配权限对话框的显示隐藏
      rightDialogVisible: false,
      // 权限列表
      rightsList: [],
      // el-tree的配置选项
      rightsProps: {
        // 以数据中的哪个属性为节点标签
        label: 'authName',
        // 指定数据中的子树的属性为children
        children: 'children'
      },
      // 保存三级权限id
      defKeys: [],
      // 角色id
      roleId: '',
      // 编辑角色对话框显示隐藏
      editRoleDialogVisible: false,
      // 添加角色对话框显示隐藏
      addRoleDialogVisible: false,
      // 添加角色表单对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色表单对象
      editRoleForm: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 编辑角色的表单验证
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 添加角色的表单验证
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  // 页面加载时触发
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      // 请求数据并接收
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      // 在data中接收数据
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 删除权限
    async removeRightById (role, rightId) {
      const res = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (res !== 'confirm') {
        return this.$message('取消了操作')
      }
      const { data: param } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + rightId
      )
      if (param.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 给角色重新赋值权限信息
      role.children = param.data
      this.$message.success('删除权限成功')
    },
    // 分配权限对话框
    async showRightDialog (role) {
      // console.log(role)
      // 存储角色id
      this.roleId = role.id
      // 请求权限列表数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 获取到的权限数据保存到data中
      this.rightsList = res.data
      // 获取三级权限id
      this.getLeafKeys(role, this.defKeys)
      // 显示对话框
      this.rightDialogVisible = true
    },
    // 获取三级权限id,并保存到defKeys中
    getLeafKeys (node, arr) {
      // 如果此节点没有children属性，则为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果有此属性则遍历
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 清空之前保存的三级权限id
    clearDefKeys () {
      this.defKeys = []
    },
    // 分配权限
    async allotRight () {
      // 获取树形控件中选中和半选中的id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将获取到的id值拼接为字符串
      const idStr = keys.join(',')
      // 发送请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      // 重新获取权限列表
      this.getRolesList()
      this.$message.success('分配权限成功')
      // 隐藏对话框
      this.rightDialogVisible = false
    },
    // 编辑角色
    showEditDialog (scopeRow) {
      console.log(scopeRow)
      // 获取此行的数据
      this.editRoleForm.roleName = scopeRow.roleName
      this.editRoleForm.roleDesc = scopeRow.roleDesc
      this.editRoleForm.id = scopeRow.id

      this.editRoleDialogVisible = true
    },
    // 取消编辑
    cancelEdit () {
      this.$message('取消了编辑')
      this.editRoleDialogVisible = false
    },
    // 提交编辑角色
    editRole () {
      // 表单预验证
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('编辑内容不能为空')
        }
        // 发送编辑角色axios请求
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.id, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.getRolesList()
        this.editRoleDialogVisible = false
        this.$message.success('修改角色信息成功')
      })
    },
    // 添加角色对话框
    showAddRoleDialog () {
      this.addRoleDialogVisible = true
    },
    // 取消了添加角色
    cancelAdd () {
      this.$message('取消了添加角色')
      this.addRoleDialogVisible = false
    },
    // 添加角色
    addRole () {
      // 表单预验证
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('角色内容不能为空')
        }
        // 发起请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('创建角色失败')
        }
        this.getRolesList()
        this.addRoleDialogVisible = false
        this.$message.success('创建角色成功')
      })
    },
    // 重置添加角色表单
    resetAddRoleForm () {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 删除时弹框
    async showDeleteMesBox (scopeRow) {
      const res = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(res)
      if (res !== 'confirm') {
        return this.$message('取消了删除操作')
      }
      // 执行删除角色请求
      const { data: param } = await this.$http.delete('roles/' + scopeRow.id)
      console.log(param)
      if (param.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getRolesList()
      this.$message.success('删除角色成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.bd-top {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
